import 'package:flutter/material.dart';
import 'package:x_core/util/toast_utils.dart';

/// Created by XieXin on 2020/4/14.
/// 返回两次退出APP
class DoubleTapBackExitApp extends StatefulWidget {
  final Widget child;

  /// 两次点击返回按钮的时间间隔
  final Duration duration;

  const DoubleTapBackExitApp({
    Key? key,
    required this.child,
    this.duration = const Duration(milliseconds: 2000),
  }) : super(key: key);

  @override
  DoubleTapBackExitAppState createState() => DoubleTapBackExitAppState();
}

class DoubleTapBackExitAppState extends State<DoubleTapBackExitApp> {
  DateTime _lastTime = DateTime.now();

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _isExit,
      child: widget.child,
    );
  }

  Future<bool> _isExit() {
    if (DateTime.now().difference(_lastTime) > widget.duration) {
      _lastTime = DateTime.now();
      ToastUtils.showLong("再次返回一次退出");
      return Future.value(false);
    }
    ToastUtils.cancel();
    return Future.value(true);
  }
}
